<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <!-- 有了form手机上就可以插法键盘搜索 -->
    <form action="/">
      <van-search
        v-model.trim="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      >
      </van-search>
    </form>
    <!--/ 搜索栏 -->
    <!-- 搜索结果 -->
    <SearchResult :searchText="searchText" v-if="isResultShow" />
    <!-- 联想建议 -->
    <SearchSuggestion
      @searchs="onSearch"
      :searchText="searchText"
      v-else-if="searchText"
    />
    <!-- 搜索历史记录 -->
    <SearchHistory
      @searchs="onSearch"
      @removeHistory="removeHistory"
      :Historys="Historys"
      v-else
    />
  </div>
</template>

<script>
import SearchHistory from './SearchHistory'
import SearchSuggestion from './SearchSuggestion'
import SearchResult from './SearchResult'
import { getItem, setItem } from '@/utils/storage'
export default {
  name: 'SearchIndex',
  data() {
    return {
      searchText: '',
      isResultShow: false,
      Historys: getItem('HISTORY') || []
    }
  },
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  watch: {
    Historys(e) {
      setItem('HISTORY', e)
    }
  },
  methods: {
    // 搜索结果
    onSearch(val) {
      this.searchText = val
      if (this.searchText) {
        // 如果重复，就不添加进去
        if (!this.Historys.includes(val)) {
          this.Historys.unshift(val)
        }
        this.isResultShow = true
      }
    },
    onCancel() {
      this.$router.back()
    },
    // 删除搜索历史
    removeHistory(index) {
      console.log(index)
      if (index === 'all') {
        this.Historys = []
      } else {
        this.Historys.splice(index, 1)
      }
    }
  }
}
</script>

<style scoped lang="less">
.search-container {
  .van-search__action {
    color: #fff;
  }
}
</style>
